package com.uduemc.biso.web.api.server.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.extities.center.SysLanguage;
import com.uduemc.biso.core.feign.SysLanguageFeign;
import com.uduemc.biso.core.property.GlobalProperties;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.web.api.server.LanguageService;

@Service
public class LanguageServiceImpl implements LanguageService {

	private static final Logger logger = LoggerFactory.getLogger(LanguageServiceImpl.class);

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private SysLanguageFeign sysLanguageFeign;

	@Autowired
	private ObjectMapper objectMapper;

	@SuppressWarnings("unchecked")
	@Override
	public List<SysLanguage> findAll() {
		String KEY = globalProperties.getCenterRedisKey().getSysLanguageFindAllKey();
		List<SysLanguage> sysLanguageFindAll = (List<SysLanguage>) redisUtil.get(KEY);
		if (CollectionUtils.isEmpty(sysLanguageFindAll)) {
			logger.info("获取 sysLanguageFindAll 数据存入缓存中");
			RestResult restResult = sysLanguageFeign.findAll();
			if (restResult.getCode() != 200 || restResult.getData() == null) {
				logger.error("sysLanguageFeign.findAll(); restResult.getCode() != 200 || restResult.getData() == null");
			} else {
				JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class,
						SysLanguage.class);
				try {
					sysLanguageFindAll = (List<SysLanguage>) objectMapper
							.readValue(objectMapper.writeValueAsString(restResult.getData()), javaType);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (!CollectionUtils.isEmpty(sysLanguageFindAll)) {
					redisUtil.set(KEY, sysLanguageFindAll, 3600 * 5);
				}
			}
		}

		return sysLanguageFindAll;
	}

}
